package com.weiaibenpao.demo.chislim.map.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.BuildConfig;
import com.weiaibenpao.demo.chislim.Interface.OnSportRecordListener;
import com.weiaibenpao.demo.chislim.LocationPreferences;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.RunningService;
import com.weiaibenpao.demo.chislim.RunningUtils;
import com.weiaibenpao.demo.chislim.bean.AddSportsBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.db.model.RunningRecord;
import com.weiaibenpao.demo.chislim.sport.SportRecordShareActivity;
import com.weiaibenpao.demo.chislim.ui.BaseRunningActivity;
import com.weiaibenpao.demo.chislim.ui.MusicTypeActivity;
import com.weiaibenpao.demo.chislim.util.GetIntentData;
import com.weiaibenpao.demo.chislim.util.SlideUnlockView;
import com.weiaibenpao.demo.chislim.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.util.Utils;
import com.weiaibenpao.demo.chislim.util.VoicePlayerUtil;

import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindMultiCallback;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.weiaibenpao.demo.chislim.R.id.mySpeed;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_DISTANCE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_ID;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_TITLE;

public class PersonalMarathonActivity extends BaseRunningActivity implements RunningService.OnDataUpdatedListener{
    @BindView(R.id.titleTv)
    TextView tvTitle;
    @BindView(R.id.switch_layout)
    LinearLayout switchLayout;
    @BindView(R.id.dis)
    TextView tvDistance;
    @BindView(R.id.sportTime)
    TextView tvRunningTime;
    @BindView(mySpeed)
    TextView tvPace;
    @BindView(R.id.tv_steps)
    TextView tvStep;
    @BindView(R.id.myCalories)
    TextView tvCalorie;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.mask)
    View mask;
    @BindView(R.id.slideUnlockView)
    SlideUnlockView slideUnlockView;
    @BindView(R.id.lock)
    ImageView lock;
    @BindView(R.id.stop)
    TextView tvStop;
    @BindView(R.id.start)
    ImageView ivStart;
    @BindView(R.id.countdown_view)
    TextView countdownText;
    private static final String KM = "km";
    private static final int TYPE_PERSONAL_MARATHON =7;
    private VoicePlayerUtil voicePlayerUtil;
    private AMap aMap;
    private ArrayList<LatLng> mLatLngList = new ArrayList<>();
    private ArrayList<LatLng> mKmPointList = new ArrayList<>();//整公里点
    private ArrayList<LatLng> mSegment = new ArrayList<>();
    private boolean isFirstRun = true;
    private Marker mMarkMyLocation;
    private RunningService mService;
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private LatLng latLng;
    private boolean isStartPointDrawn;
    private boolean isRecoveredRunning;
    private float mCurrentDistance;
    private StringBuilder mLocusPhoto = new StringBuilder();       //轨迹
    private StringBuilder mFrequencyPhoto = new StringBuilder();   //步频图
    private StringBuilder mStridePhoto = new StringBuilder();      //步幅图
    private StringBuilder mPaceForm = new StringBuilder();         //配速列表
    private StringBuilder mAltitudePhoto = new StringBuilder();    //海拔图
    private ProgressDialog mProgressDialog;
    private Handler mHandler = new Handler();
    private float mMarathonDistance;
    private String mMarathonId;
    private boolean isMatchFinished;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RunningService.LocalBinder binder = (RunningService.LocalBinder) service;
            mService = binder.getService();
            mService.registerOnDataUpdatedListener(PersonalMarathonActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            Log.e("PersonalMarathon", "onServiceDisconnected");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindowFlag();
        setContentView(R.layout.layout_running);
        initView();
        initMap(savedInstanceState);
        initLockView(savedInstanceState);
        initService();
        int state = RunningPreferences.getInstance().getRunningState();
        if (state == RunningService.RUNNING || state == RunningService.PAUSE) {
            lock.setVisibility(View.VISIBLE);
            tvStop.setVisibility(View.VISIBLE);
            ivStart.setImageResource(R.drawable.ic_finish);
            if (state == RunningService.PAUSE) {
                tvStop.setText("继续");
            }
            isRecoveredRunning = true;
            restoreDataDisplay();//由于服务端的回调有过滤，例如如果精度不满足，就不回调，所以这里进行一次手动恢复现场
        }
    }

    private void initView() {
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        checkPermission();
        mProgressDialog = new ProgressDialog(this);
//        voicePlayerUtil = new VoicePlayerUtil(this);
        if(getIntent() != null){
            Log.e("onCreate","original id "+getIntent().getStringExtra(MARATHON_ID));
            mMarathonId = getIntent().getStringExtra(MARATHON_ID);//H5必须保证id有效才可以跳转到我这！，所以判空应该在跳转这里前而不是这里！
            RunningPreferences.getInstance().putString(MARATHON_ID,mMarathonId);
            String marathonTitle = getIntent().getStringExtra(MARATHON_TITLE);
            if(!TextUtils.isEmpty(marathonTitle)) {
                tvTitle.setText(marathonTitle);
                RunningPreferences.getInstance().putString(MARATHON_TITLE,marathonTitle);
            }
            String distance = getIntent().getStringExtra(MARATHON_DISTANCE);
            if(!TextUtils.isEmpty(distance)){
                mMarathonDistance = Float.parseFloat(distance)*1000;//转换为米
                RunningPreferences.getInstance().putString(MARATHON_DISTANCE,distance);
            }
            RunningPreferences.getInstance().putBoolean(RunningPreferences.IS_PERSONAL_MARATHON,true);
            Log.e("onCreate","marathon title "+tvTitle.getText()+"\nmMarathonId--"+mMarathonId+"\nmarathonDistance--"+mMarathonDistance);
        }
    }

    private void restoreDataDisplay() {
        showAddToWhiteListNotice();
        mCurrentDistance = RunningPreferences.getInstance().getRunningDistance();
        tvRunningTime.setText(RunningUtils.getHmsTime((RunningPreferences.getInstance().getRunningTime())));
        String formatDis = decimalFormat.format(mCurrentDistance / 1000);
        tvDistance.setText(formatDis);
        tvCalorie.setText(RunningPreferences.getInstance().getRunningCalorie());
        tvPace.setText(RunningPreferences.getInstance().getRunningPace());
        tvStep.setText(String.valueOf(RunningPreferences.getInstance().getRunningStep()));
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                DataSupport.findAllAsync(RunningRecord.class).listen(new FindMultiCallback() {
                    @Override
                    public <T> void onFinish(List<T> list) {
                        restoreMapData((List<RunningRecord>) list);
                    }
                });
            }
        });
    }

    private void restoreMapData(List<RunningRecord> records) {
        if(records == null || records.size() == 0) {
            return;
        }
        int recordSize = records.size();
        Log.e("restoreMapData", "  records size is  " + records.size());
        LatLng start = new LatLng(records.get(0).getLat(),records.get(0).getLng());
        LatLng end = new LatLng(records.get(recordSize-1).getLat(),records.get(recordSize-1).getLng());
        List<LatLng> tempList = new ArrayList<>();
        for (int i = 0; i < recordSize; i++) {
            RunningRecord record = records.get(i);
            tempList.add(new LatLng(record.getLat(), record.getLng()));
        }
        mLatLngList.addAll(0,tempList);
        setStartMark(start);
        moveLocationMarker(end);
        drawTrace(mLatLngList);
    }
    private void initService() {
        Intent serviceIntent = new Intent(PersonalMarathonActivity.this, RunningService.class);
        serviceIntent.putExtra(RunningService.RUNNING_ACTIVITY, getClass().getCanonicalName());
        serviceIntent.putExtra(RunningService.NEED_SAVE_TRACE,true);
        serviceIntent.putExtra(RunningService.NEED_EXTRA_DATA,true);
        serviceIntent.putExtra(RunningService.NEED_SAVE_STATE,true);
        serviceIntent.putExtra(RunningService.IS_PERSONAL_MARATHON,true);
        startService(serviceIntent);
        bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
    }

    private void setWindowFlag() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);    //让一个activity 浮在锁屏界面的上方，返回即进入解锁界面
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);    //设置屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

    private void initMap(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                @Override
                public void onMapLoaded() {
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                    setMyLocationStyleIcon();
                }
            });
        }
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setLogoPosition(2);//设置高德地图logo位置
        mUiSettings.setZoomControlsEnabled(false);
        aMap.setMyLocationEnabled(true);

        String latitudeStr = LocationPreferences.getInstance().getLocationLatitude();
        String longitudeStr = LocationPreferences.getInstance().getLocationLongitude();
        if(!TextUtils.isEmpty(latitudeStr) && !TextUtils.isEmpty(longitudeStr)){
            Double latitude = Double.parseDouble(latitudeStr);
            Double longitude = Double.parseDouble(longitudeStr);
            LatLng latLng = new LatLng(latitude,longitude);
            updateCamera(latLng);
            moveLocationMarker(latLng);
        }
    }

    /**
     * 显示地图显示中心点
     */
    private void updateCamera(LatLng latLng) {
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
    }

    private void initLockView(Bundle savedInstanceState){
        slideUnlockView.setOnUnLockListener(new SlideUnlockView.OnUnLockListener() {
            @Override
            public void setUnLocked(boolean unLocked) {
                if(unLocked){
                    mask.setVisibility(View.GONE);
                    slideUnlockView.reset();
                    slideUnlockView.setVisibility(View.GONE);
                    switchLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void setMyLocationStyleIcon() {
//		 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        ImageView iv = new ImageView(this);
        FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(1, 1);
        iv.setImageResource(R.mipmap.location);
        iv.setLayoutParams(fmIv);
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
        myLocationStyle.myLocationIcon(markerIcon);          // 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));       // 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));      // 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.9f);
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(mService != null) mService.unRegisterOnDataUpdatedListener();
        if(mHandler != null) mHandler.removeCallbacksAndMessages(null);
        unbindService(connection);
        if(mProgressDialog != null){
            mProgressDialog.cancel();
            mProgressDialog = null;
        }
    }

    @OnClick({R.id.lock, R.id.stop, R.id.start,R.id.music_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lock:
                switchLayout.setVisibility(View.GONE);
                mask.setVisibility(View.VISIBLE);
                slideUnlockView.setVisibility(View.VISIBLE);
                break;
            case R.id.start:
                if (mService != null) {
                    if (mService.hasOngoingRunning()) {
                        if(mCurrentDistance >= mMarathonDistance){
                            showUploadDialog();
                        }else {
                            showNotUploadDialog();
                        }
                    } else {
                        if (goEnableGPS()) return;
                        if (isFirstRun) {
                            isFirstRun = false;
                            startCountdown();
                        }
                    }
                }
                break;
            case R.id.stop:
                if (mService != null) {
                    if (mService.getRunningState() == RunningService.RUNNING) {
                        tvStop.setText("继续");
//                        voicePlayerUtil.startVoice("暂停跑步");
                        SpeechUtil.getInstance().speak("暂停跑步");
                        mService.setState(RunningService.PAUSE);
                    } else if (mService.getRunningState() == RunningService.PAUSE) {
                        if(goEnableGPS()) return;
                        tvStop.setText("暂停");
//                        voicePlayerUtil.startVoice("继续跑步");
                        SpeechUtil.getInstance().speak("继续跑步");
                        mService.setState(RunningService.RUNNING);
                    }
                }
                break;
            case R.id.music_tv:
                Intent intent = new Intent(this , MusicTypeActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void doFinish() {
        if (mService != null) mService.setState(RunningService.FINISH);
        finish();
    }


    private void startCountdown() {
        countdownText.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= -1; i--) {
//                    if (isFinishing()) return;
                    if (isDestroyed()) return;
                    try {
                        final int index = i;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (index > 0) {
//                                    voicePlayerUtil.startVoice(String.valueOf(index));
                                    SpeechUtil.getInstance().speak(String.valueOf(index));
                                    countdownText.setText(String.valueOf(index));
                                } else if (index == 0) {
//                                    voicePlayerUtil.startVoice("跑步开始");
                                    SpeechUtil.getInstance().speak("跑步开始");
                                    countdownText.setText("Go!");
                                } else {
                                    countdownText.setVisibility(View.GONE);
                                    if(mService!=null){
                                        //                                        mService.clearDatabase();//执行一次数据库清理，以防上次结束清理失败
                                        mService.setState(RunningService.RUNNING);
                                        lock.setVisibility(View.VISIBLE);
                                        tvStop.setVisibility(View.VISIBLE);
                                        ivStart.setImageResource(R.drawable.ic_finish);
                                    }
                                }
                            }
                        });
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onGPSStateChanged(boolean enabled) {
        if(!enabled){
            if(mService!=null && mService.getRunningState() == RunningService.RUNNING ) onClick(tvStop);
        }
    }

    @Override
    public void onDataUpdated(Bundle data) {
        if(isDestroyed()){
            return;
        }
        if (data == null) {
            return;
        }
        mCurrentDistance = data.getFloat(RunningService.DISTANCE);
        if(!isMatchFinished && mCurrentDistance >= mMarathonDistance ){
//            voicePlayerUtil.startVoice("您的赛事已完成");
            SpeechUtil.getInstance().speak("您的赛事已完成");
//            if(BuildConfig.DEBUG) {
//                voicePlayerUtil.startVoice("您已跑了"+mCurrentDistance/1000+"公里"+"本次马拉松距离为"+mMarathonDistance/1000+"公里");
//            }
            isMatchFinished = true;
        }
        String formatDis = decimalFormat.format(mCurrentDistance/ 1000) ;
        tvDistance.setText(formatDis);
        tvPace.setText(data.getString(RunningService.PACE));
        tvStep.setText(data.getString(RunningService.STEP));
        tvCalorie.setText(data.getString(RunningService.CALORIE));
        latLng = data.getParcelable(RunningService.LAT_LNG);
        mLatLngList.add(latLng);
//        mSegment.add(latLng);
//        if (mSegment.size() == 3) {
//            mSegment.remove(0);
//        }
        LatLng kmLatLng = data.getParcelable(RunningService.KM_LAT_LNG);
//        if (kmLatLng != null) {
//            mKmPointList.add(kmLatLng);
//            setKmMarkView();  //设置整公里标记
//        }
        if (!isRecoveredRunning && !isStartPointDrawn) {
            setStartMark(latLng);
        }
        moveLocationMarker(latLng);
//        drawTrace(mSegment);//绘制轨迹
        drawTrace(mLatLngList);//绘制轨迹
//        assembleData(data);
    }

    private void assembleData(Bundle data) {
        mLocusPhoto.append(String.valueOf(latLng.longitude)).append(":").append(String.valueOf(latLng.latitude)).append(":").append(data.getString(RunningService.SPEED)).append(",");
        long time = RunningUtils.transformTimeStrToSeconds(String.valueOf(tvRunningTime.getText()));
        String timeStr = String.valueOf(time);
        mFrequencyPhoto.append(timeStr).append(":").append(data.getString(RunningService.FREQUENCY)).append(",");
        mStridePhoto.append(timeStr).append(":").append(data.getString(RunningService.STRIDE)).append(",");
        if(!TextUtils.isEmpty(data.getString(RunningService.KM_PACE))) {
            mPaceForm.append(data.getString(RunningService.KM_VALUE)).append(":").append(data.getString(RunningService.KM_PACE)).append(":").append(timeStr).append(",");
        }
        mAltitudePhoto.append(timeStr).append(":").append(data.getString(RunningService.ALTITUDE)).append(",");
        Log.e("上传的数据","坐标--" + mLocusPhoto.toString() + "  步频--" + mFrequencyPhoto + " 步幅--" + mStridePhoto + "   配速--" + mPaceForm + "  海拔--" + mAltitudePhoto);
    }


    @Override
    public void onRunningTime(final int runningTime) {
        if(isDestroyed()){
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvRunningTime.setText(RunningUtils.getHmsTime(runningTime));
            }
        });
    }

    private void moveLocationMarker(final LatLng latlng) {
        if(latlng == null){
            return;
        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17f));
//        if (mMarkMyLocation != null) {
//            mMarkMyLocation.destroy();
//        }
        if (mMarkMyLocation == null) {
            final MarkerOptions markerOptions = new MarkerOptions();
            //markerOptions.snippet(dogId);
            // 设置Marker点击之后显示的标题R.drawable.local2R.mipmap.location
            //markerOptions.setFlat(false);
            markerOptions.anchor(0.5f, 0.7f);
            markerOptions.zIndex(25);
            markerOptions.zIndex(90);
            ImageView iv = new ImageView(this);
            FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(100, 100);
            iv.setImageResource(R.mipmap.ic_gps);
            iv.setLayoutParams(fmIv);
            BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
            markerOptions.icon(markerIcon);
            markerOptions.position(latlng);
            mMarkMyLocation = aMap.addMarker(markerOptions);
        } else {
            mMarkMyLocation.setPosition(latlng);
        }
    }

    private void setStartMark(LatLng latLng){
        if(latLng == null) {
            return;
        }
        View view = View.inflate(this, R.layout.mark_layout, null);
        TextView sportMark = (TextView) view.findViewById(R.id.sportTitle);
        sportMark.setText("起");
        Bitmap bitmap = convertViewToBitmap(view);
        drawMarkerOnMap(latLng, bitmap, String.valueOf("起"));
        isStartPointDrawn = true;
    }

    private Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        return view.getDrawingCache();
    }

    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String id) {

        if (aMap != null && point != null) {

            return aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
                    .title(id)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
        }
        return null;
    }

    private Polyline traceLine;
    public void drawTrace(List<LatLng> latLngs) {
        if (traceLine != null) {
            traceLine.remove();
            traceLine = null;
        }
        PolylineOptions polylineOptions = new PolylineOptions();
        polylineOptions.addAll(latLngs);
        polylineOptions.visible(true).width(12).zIndex(200);
        polylineOptions.color(getResources().getColor(R.color.map_trace_color));
        traceLine = aMap.addPolyline(polylineOptions);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    private int WRITE_COARSE_LOCATION_REQUEST_CODE = 0;

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                    WRITE_COARSE_LOCATION_REQUEST_CODE);//自定义的code
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
        if (WRITE_COARSE_LOCATION_REQUEST_CODE == 0) {

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.e("onKeyDown", "------------------------------->");
            if (mService != null && mService.hasOngoingRunning()) {
                showFinishConfirm();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showFinishConfirm() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("跑步还在进行中，请结束后退出？");
        builder.setNegativeButton("结束", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(mCurrentDistance >= mMarathonDistance){
                    showUploadDialog();
                }else {
                    showNotUploadDialog();
                }
            }
        });
        builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }

    private void showUploadDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("是否保存并上传数据？");
        builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                doFinish();
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                uploadRunningData();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void  showNotUploadDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("您的赛事未完成，是否放弃本次马拉松？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do nothing
            }
        });
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                uploadRunningData();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }


    private boolean alreadyAssembled;
    private void uploadRunningData(){
        if(mProgressDialog != null) mProgressDialog.show();
        if(alreadyAssembled){
            doUpload();
        }else {
            DataSupport.findAllAsync(RunningRecord.class).listen(new FindMultiCallback() {
                @Override
                public <T> void onFinish(List<T> list) {
                    if(!isDestroyed()) {
                        assembleDataFromDatabase((List<RunningRecord>) list);
                        alreadyAssembled = true;
                        doUpload();
                    }
                }
            });
        }
    }

    private void assembleDataFromDatabase(List<RunningRecord> list) {
        List<RunningRecord> records  = list;
        for(int i=0;i<records.size();i++){
            RunningRecord record = records.get(i);
            mLocusPhoto.append(String.valueOf(record.getLng())).append(":").append(String.valueOf(record.getLat())).append(":").append(record.getSpeed()).append(",");
            //Log.e("assemble--json",new Gson().toJson(record));//这个打印很耗时  而且还有个坑，单引号和双引号会显示乱码
            String timeStr = String.valueOf(record.getTime());
            mFrequencyPhoto.append(timeStr).append(":").append(record.getFrequency()).append(",");
            mStridePhoto.append(timeStr).append(":").append(record.getStride()).append(",");
            if(!TextUtils.isEmpty(record.getKmPace())){
                mPaceForm.append(record.getKmValue()).append(":").append(record.getKmPace()).append(":").append(timeStr).append(",");
            }
            mAltitudePhoto.append(timeStr).append(":").append(record.getAltitude()).append(",");
        }

        if(BuildConfig.DEBUG) Log.e("上传的数据","坐标--" + mLocusPhoto.toString() + "  步频--" + mFrequencyPhoto + " 步幅--" + mStridePhoto + "   配速--" + mPaceForm + "  海拔--" + mAltitudePhoto);
        if(BuildConfig.DEBUG) Log.e("上传的数据","坐标size--" + mLocusPhoto.length() + "  步频size--" + mFrequencyPhoto.length() + " 步幅size--" + mStridePhoto.length() + "   配速size--" + mPaceForm.length() +
                "  海拔size--" + mAltitudePhoto.length());
    }

    private void doUpload() {
        if(isDestroyed()){
            return;
        }
        if(!Utils.isNetWorkConnected()){
            Toast.makeText(this, "亲，网络连了么？", Toast.LENGTH_SHORT).show();
            return;
        }
        final String distance = String.valueOf(tvDistance.getText());
        GetIntentData getIntentData = new GetIntentData();
        getIntentData.addMarathon(UserBean.getUserBean().userId,TYPE_PERSONAL_MARATHON,
                mMarathonId, RunningUtils.transformTimeStrToSeconds(String.valueOf(tvRunningTime.getText())), distance,
                String.valueOf(tvCalorie.getText()),String.valueOf(tvStep.getText()),
                String.valueOf(mAltitudePhoto),String.valueOf(mFrequencyPhoto),String.valueOf(mStridePhoto),
                String.valueOf(mPaceForm),String.valueOf(mLocusPhoto));
        if(BuildConfig.DEBUG) Log.e("addMarathon","altitude->"+String.valueOf(mAltitudePhoto)+"\nfrequency->"+String.valueOf(mFrequencyPhoto)+
                "\nstride->"+String.valueOf(mStridePhoto)+"\npace->"+
                String.valueOf(mPaceForm)+"\nLocus->"+String.valueOf(mLocusPhoto));
        getIntentData.setOnSportRecordListener(new OnSportRecordListener() {
            @Override
            public void onUploadSuccess(Object object) {
                AddSportsBean.DataBean dataBean = (AddSportsBean.DataBean) object;
                if(dataBean != null){
                    boolean isFinished = TextUtils.equals(getString(R.string.yes_en),dataBean.getIsFinish());
                    SportRecordShareActivity.openActivity(PersonalMarathonActivity.this,dataBean.getUrl(),distance,true,isFinished);
                }
                doFinish();
                if(BuildConfig.DEBUG) Log.e("addMarathon"," 上传成功  "+dataBean.getUrl());
                if(mProgressDialog != null) mProgressDialog.cancel();
            }

            @Override
            public void onUploadFailed(String errMsg) {
                if(BuildConfig.DEBUG) Log.e("addMarathon"," 上传失败 msg is "+errMsg);
                if(mProgressDialog != null) mProgressDialog.cancel();
            }
        });
    }
}
